import request from "../../common/utils/request";
const search = {
  state: {
    // 搜索设置
    searchSettingList: [],
    // 搜索框下拉选项
    filterOptions: {},
    // 全部行业
    allIndustryList: [],
    // 账单列表搜索下拉初始化
    billInitOpt: {},
    billSettingList: [],
    contractStatusColor: {
      1: "blue", // 正常执行中
      2: "green", // 变更待审批
      3: "cyan", // 变更待修改
      4: "cyan", // 退租待审批
      5: "orange", // 退租待执行 // 退租待审批
      6: "orange", // 已退租
      7: "default", // 作废待审批
      8: "red", // 作废待修改
      9: "red",  // 到期未处理
      10: "pink", // 已驳回
      11: "red", // 已作废
      12: "red", // 已撤销
      13: "default", // 待执行
      14: "default", // 续租待审批
      15: "purple", // 已到期
      16: "blue", // 已续租
      17: "blue", // 已续租
      18: "red", // 退租待付款
      19: "default", // 退租已审批
      20: "red", // 退租待收款
    },
  },
  mutations: {
    SEARCH_SETTING_LIST: (state, list) => {
      state.searchSettingList = list;
    },
    FILTER_OPTIONS: (state, data) => {
      state.filterOptions = { ...data };
    },
    ALL_INDUSTRY_LIST: (state, list) => {
      state.allIndustryList = list;
    },
    SET_BILL_INIT_OPT: (state, data) => {
      state.billInitOpt = { ...data };
    },
    BILL_SETTING_LIST: (state, list) => {
      state.billSettingList = list;
    },
  },
  actions: {
    /**
     * @description: 存储搜索设置
     * @param {*} type map arr
     * @param {*} source contract bill
     * @param {*} data
     */
    SetSearchSettingList({ commit }, { type, data, source = "contract" }) {
      return new Promise((resolve) => {
        let list = [];
        if (type == "map") {
          // map to arr
          for (let key in data) {
            list.push({
              key,
              ...data[key],
            });
          }
          list.sort(function (a, b) {
            return a.order - b.order;
          });
        }
        if (type == "arr") {
          // 根据数组排序生成新数组
          list = data;
          list.forEach((item, index) => {
            item.order = index + 1;
          });
        }
        if (source == "contract") {
          commit("SEARCH_SETTING_LIST", list);
        }
        if (source == "bill") {
          commit("BILL_SETTING_LIST", list);
        }
        resolve(list);
      });
    },
    GetSearchSettingState({ state }, { source = "contract" }) {
      return new Promise((resolve) => {
        const { searchSettingList, billSettingList } = state;
        const list = source == "bill" ? billSettingList : searchSettingList;
        let formState = {};
        if (list.length) {
          list.forEach((item) => {
            formState[item.key] = {
              ...item,
            };
          });
        }
        resolve(formState);
      });
    },
    /**
     * @description: 获取搜索栏所有下拉选项值
     */
    GetFilterOptions({ state, commit, dispatch }) {
      return new Promise((resolve) => {
        if (state.filterOptions && Object.keys(state.filterOptions).length) {
          resolve(state.filterOptions);
        } else {
          let data = {};
          const success = () => {
            if (data.industry_id && Object.keys(data).length > 1) {
              commit("FILTER_OPTIONS", data);
              resolve(data);
            }
          };
          // 行业分类
          dispatch("GetIndustryList").then((list) => {
            data.industry_id = transformOptionValue(list, {
              valueKey: "id",
            });
            success();
          });
          // 其他
          request.get("/org", "/contract/listSearchInit").then((res) => {
            const {
              clauseType,
              contractSource,
              contractStatus,
              contractTag,
              contractType,
              createUser,
              followup,
              entryStatus,
              discountType,
              branchList,
            } = res.data;
            data.clause_type = transformOptionValue(clauseType);
            data.source = transformOptionValue(contractSource);
            data.status = transformOptionValue(contractStatus);
            data.contract_tag = transformOptionValue(contractTag);
            data.type = transformOptionValue(contractType);
            data.cuser_uid = transformOptionValue(createUser, {
              valueKey: "uid",
              labelKey: "realname",
            });
            data.followup_uid = transformOptionValue(followup, {
              valueKey: "uid",
              labelKey: "realname",
            });
            data.entry_status = transformOptionValue(entryStatus);
            data.discountType = transformOptionValue(discountType);
            data.org_branch_id = transformOptionValue(branchList);
            success();
          });
        }
      });
    },
    GetIndustryList({ state, commit }) {
      return new Promise((resolve) => {
        const { allIndustryList } = state;
        if (allIndustryList.length) {
          resolve(allIndustryList);
        } else {
          request.get("/org", "/manage/taglib/industry/all").then((res) => {
            commit("ALL_INDUSTRY_LIST", res.list);
            resolve(res.list);
          });
        }
      });
    },
    // 账单下拉数据初始化
    BillInit: ({ state, commit }, params = {}) => {
      return new Promise((resolve) => {
        const { billInitOpt } = state;
        request.get("/org", "/bill/listSearchInit", params).then((res) => {
          const { data } = res;
          let initData = {};
          initData.bill_status = transformOptionValue(data.billStatus);
          initData.receivable_payment_date = transformOptionValue(
            data.dateSelect
          );
          initData.settle_status = transformOptionValue(data.settleStatus);
          initData.bill_type = transformOptionValue(data.billType);
          initData.cost_type = transformOptionValue(data.costType);
          initData.timeout_status = transformOptionValue(data.timeoutStatus);
          initData.latefee_status = transformOptionValue(data.latefeeStatus);
          initData.contract_status = transformOptionValue(data.contractStatus);
          initData.receipt_status = transformOptionValue(data.lockStatus);
          initData.invoice_status = transformOptionValue(data.invoiceStatus);
          initData.invoice_record_status = transformOptionValue(
            data.invoiceRecordStatus
          );
          initData.cost_type = transformOptionValue(data.costType);
          initData.bill_source = data.billSource.map((item, index) => {
            let obj = {
              value: item.value,
              label: item.name,
            };
            if (item.options) {
              obj.value = "source_" + index;
              obj.label = item.label;
              obj.children = item.options.map((item2) => ({
                value: item2.value,
                label: item2.name,
              }));
            }
            return obj;
          });
          initData.currency = transformOptionValue(data.currencyUnit);
          initData.stream_account = transformOptionValue(data.streamAccount);
          initData.loan_type = transformOptionValue(data.loanType);
          initData.remit_money = transformOptionValue(data.remitMoney);
          initData.remit_type = transformOptionValue(data.remitType);
          initData.retreat_type = transformOptionValue(data.retreatType);
          initData.company_name = transformOptionValue(data.companyName);
          initData.stream_config = transformOptionValue(data.stream_config);
          initData.is_forfeit = transformOptionValue(data.isForfeit);
          initData.adjust_type = transformOptionValue(data.adjustType);
          initData.org_branch_id = transformOptionValue(data.branchList);
          initData.approval_status = transformOptionValue(data.approvalStatus);
          commit("SET_BILL_INIT_OPT", initData);
          resolve(initData);
        });
      });
    },
  },
};

const transformOptionValue = (list, relation = {}) => {
  if (!list || !list.length) {
    return [];
  }
  relation.valueKey = relation.valueKey || "key";
  relation.labelKey = relation.labelKey || "name";
  return list.map((item) => ({
    value: item[relation.valueKey],
    label: item[relation.labelKey],
  }));
};

export default search;
